import axios from 'axios';
import { showFailToast } from 'vant';

import cookie from '@/utils/cookie';

axios.interceptors.request.use((request) => {
  const baseUrl = import.meta.env.VITE_AXIOS_API_BASE;
  request.baseURL = baseUrl;
  const token = cookie.getCookie('token');
  if (token) {
    request.headers.Authorization = `Bearer ${token}`;
  }

  return request;
});

const whiteList = [
  '/api/v1/user/info',
  '/logout',
];

axios.interceptors.response.use(
  async (response) => {
    if (
      response.data.code === -101
      || response.data.code === 401
      || response.data.code === 'ERR_HTTP_INVALID_HEADER_VALUE'
    ) {
      if (response.config.url && whiteList.includes(response.config.url)) {
        if (window.location.pathname.includes('admin')) {
          window.location.href = '/';
        }
        return Promise.reject(response.data);
      }
      showFailToast({
        message: '登录已过期，请重新登录',
        position: 'top',
      });
    }
    if (response.data.code === undefined) {
      showFailToast({
        message: response.data.msg || '请求失败',
        position: 'top',
      });
      return Promise.reject(response.data);
    }

    if (![0, 200].includes(response.data.code)) {
      showFailToast({ message: response.data.msg || '请求失败', position: 'top' });
      return Promise.reject(response.data);
    }
    return response;
  },
  (err: any) => {
    showFailToast({ message: err.response.data.msg || '请求失败', position: 'top' });
    return Promise.reject(err);
  },
);
